package controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Db;
import interceptor.CategoryNavbarInterceptor;
import interceptor.LoginValidator;
import model.Topic;
import model.User;

import java.util.List;

public class MainController extends Controller {
    @Before(CategoryNavbarInterceptor.class)
    public void index() {
        String sql = Db.getSql("getHotTopics");

        List<Topic> topics = Topic.dao.find(sql);
        setAttr("topics", topics);
        renderFreeMarker("main.ftl");
    }

    public void login() {
        renderFreeMarker("login.ftl");
    }

    @Before(LoginValidator.class)
    public void loginCheck() {
        String username = getPara("username");
        String password = getPara("password");
        List<User> users = User.dao.find("SELECT * FROM t_user WHERE username = ? AND password = ?",
                username, password);
        //登录成功
        if (users.size() != 0) {
            //跳转到主页面
            setSessionAttr("user", users.get(0));
           // renderFreeMarker("main.ftl");
            if(users.get(0).getAdmin()){
                redirect("/category/list");
            }
            else
            redirect("/main");
            //往session中放入一个key为user的变量，值为用户登录的用户名


        } else {
            //登录失败
            setAttr("errmsg", "用户名或密码错误");
            renderFreeMarker("login.ftl");
        }

    }

    public void logout() {
        removeSessionAttr("user");
        redirect("/login");
    }

    public void register() {
        renderFreeMarker("register.ftl");
    }

    public void doRegister() {
        String username = getPara("username");
        String password = getPara("password");
        String nickname = getPara("nickname");
        String email = getPara("email");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setEmail(email);
        try {
            user.save();
        } catch (Exception e) {
            LogKit.error("用户注册失败，原因是:" + e.getMessage());
        }
       // renderHtml("注册成功");
       // boolean success = false;
        boolean success = true;
        String message = "注册成功";
        Kv result = Kv.by("success", success).set("message", message);
        renderJson(result);
    }
}
